package com.jfinal.aceadmin.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.aceadmin.util.VoUtil;
import com.jfinal.aceadmin.vo.ChatLogVo;
import com.jfinal.plugin.activerecord.Record;

public class ChatImpl {

	private static ChatImpl chatImpl = new ChatImpl();

	public static ChatImpl getDAO() {
		return chatImpl;
	}

	public List<ChatLogVo> getRecentChatLogs() {
		List<ChatLog> chatLogs = ChatLog.dao.paginate(1, 5,
				"SELECT * FROM ChatLog", "ORDER BY createdDate DESC").getList();
		List<ChatLogVo> chatLogVos = new ArrayList<ChatLogVo>();
		for (ChatLog chatLog : chatLogs) {
			ChatLogVo chatLogVo = VoUtil.convert(chatLog);
			chatLogVos.add(chatLogVo);
		}
		return chatLogVos;
	}

	public void addChat(String content, String username) {
		Record user = User.dao.findByAttrUnique("name", username);
		int userId = user.getInt("id");
		ChatLog chatLog = new ChatLog();
		chatLog.setUserId(userId);
		chatLog.setUsername(username);
		chatLog.setContent(content);
		chatLog.setCreatedDate(new Date());
		chatLog.save();
	}
}
